package views.job;

import org.intellij.lang.annotations.Language;
import utils.DBUtil;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

/**
 * @author 黑兔玛奇朵
 */
public class Job_Update_Delete extends JFrame {
    int categoryid = 1, employerid = 1;
    private JScrollPane jsp = new JScrollPane();
    private JTable table = new JTable();
    ImageIcon imageIcon = new ImageIcon("src/images/job.png");
    private JButton btn_change = new JButton("修改");
    private JButton btn_delete = new JButton("删除");
    private int row;
    public MyModel model;
    private String[] table_title = {"职业编号", "职业名称", "职业类型", "用人单位", "需要人数", "已招人数", "备注"};
    private JLabel jL_jobId = new JLabel("职业编号");
    private JLabel jl_jobName = new JLabel("职业名称：");
    private JLabel jl_cateory = new JLabel("类   别：");
    private JLabel jl_employer = new JLabel("用人单位：");
    private JLabel jl_demand = new JLabel("需   求：");
    private JLabel jl_hired = new JLabel("已   招：");
    private JLabel jl_remark = new JLabel("备   注：");

    private JTextField jT_jobId = new JTextField();
    private JTextField jT_jobName = new JTextField();
    JComboBox<String> JC_Category = new JComboBox<String>();
    JComboBox<String> JC_employer = new JComboBox<String>();
    private JTextField jT_demandNum = new JTextField();
    private JTextField jT_hiredNum = new JTextField();
    private JTextArea jTA_remark = new JTextArea(20, 20);

    private JButton btn_find = new JButton("查找");
    private JTextField jT_find = new JTextField();
    private Panel panBtn = new Panel();
    private Panel panLab = new Panel();

    public Job_Update_Delete() {
        this.setSize(650, 700);
        this.setIconImage(imageIcon.getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT));
        setTitle("职业信息修改与删除");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        // 修改列名称
        panBtn.add(btn_change);
        panBtn.add(btn_delete);
        // 设置中间的panel布局为空
        panLab.setLayout(null);
        // 单选框
        JRadioButton JR_findByName = new JRadioButton("按名字查找");
        JRadioButton JR_findByCategory = new JRadioButton("按类别查找");
        JRadioButton JR_findByEmployer = new JRadioButton("按用人单位查找");
        JR_findByName.setSelected(true); // 默认选择JB1
        // 加入组，避免出现可以两个都选择的情况
        ButtonGroup bg = new ButtonGroup();
        bg.add(JR_findByName);
        bg.add(JR_findByCategory);
        bg.add(JR_findByEmployer);

        // 给组件设置位置
        JR_findByName.setSize(100, 30);
        JR_findByName.setLocation(40, 20);

        JR_findByCategory.setSize(100, 30);
        JR_findByCategory.setLocation(140, 20);

        JR_findByEmployer.setSize(100, 30);
        JR_findByEmployer.setLocation(240, 20);

        jT_find.setSize(140, 30);
        jT_find.setLocation(350, 20);

        btn_find.setSize(80, 30);
        btn_find.setLocation(500, 20);

        jL_jobId.setSize(100, 100);
        jL_jobId.setLocation(10, 30);
        jL_jobId.setHorizontalAlignment(JLabel.RIGHT);
        jT_jobId.setSize(150, 25);
        jT_jobId.setLocation(110, 65);

        jl_jobName.setSize(100, 100);
        jl_jobName.setLocation(280, 30);
        jl_jobName.setHorizontalAlignment(JLabel.RIGHT);
        jT_jobName.setSize(150, 25);
        jT_jobName.setLocation(380, 70);

        jl_cateory.setSize(100, 100);
        jl_cateory.setLocation(10, 90);
        jl_cateory.setHorizontalAlignment(JLabel.RIGHT);
        try {
            for (int k = 0; k < getCategory_name().size(); k++) {
                JC_Category.addItem(getCategory_name().get(k));
            }
            JC_Category.setSize(150, 25);
            JC_Category.setLocation(110, 130);
            JC_Category.setSelectedIndex(-1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        jl_employer.setSize(100, 100);
        jl_employer.setLocation(280, 90);
        jl_employer.setHorizontalAlignment(JLabel.RIGHT);
        try {
            for (int k = 0; k < getEmployer_name().size(); k++) {
                JC_employer.addItem(getEmployer_name().get(k));
            }
            JC_employer.setSize(150, 25);
            JC_employer.setLocation(380, 130);
            JC_employer.setSelectedIndex(-1);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        jl_demand.setSize(100, 100);
        jl_demand.setLocation(10, 150);
        jl_demand.setHorizontalAlignment(JLabel.RIGHT);
        jT_demandNum.setSize(150, 25);
        jT_demandNum.setLocation(110, 190);


        jl_hired.setSize(100, 100);
        jl_hired.setLocation(280, 150);
        jl_hired.setHorizontalAlignment(JLabel.RIGHT);
        jT_hiredNum.setSize(150, 25);
        jT_hiredNum.setLocation(380, 190);

        jl_remark.setSize(100, 100);
        jl_remark.setLocation(10, 210);
        jl_remark.setHorizontalAlignment(JLabel.RIGHT);

        jTA_remark.setSize(420, 100);
        jTA_remark.setLocation(110, 250);
        model = new MyModel("select job_id, job_name, category_name, employer_name, demand_num, hired_num, remark FROM `job_info` " +
                "LEFT JOIN `job_category` jc ON job_info.category_id = jc.category_id " +
                "LEFT JOIN `employer` e on job_info.employer_id = e.employer_id; ");
        table.setModel(model);
        for (int i = 0; i < table_title.length; i++) {
            table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
        }
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);

        // 设置可见视图的接口
        jsp.setViewportView(table);
        // 定义表格 宽600，高度200
        jsp.setPreferredSize(new Dimension(800, 300));
        // 设置横向和垂直滚动条可见
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        //设置jobid文本框不可编辑
        jT_jobId.setEditable(false);

        // 把标签和文本框加到panLab面板中
        panLab.add(jL_jobId);
        panLab.add(jT_jobId);
        panLab.add(jl_jobName);
        panLab.add(jl_cateory);
        panLab.add(jl_employer);
        panLab.add(jl_demand);
        panLab.add(jl_hired);
        panLab.add(jT_jobName);
        panLab.add(JC_Category);
        panLab.add(JC_employer);
        panLab.add(jT_demandNum);
        panLab.add(jT_hiredNum);
        panLab.add(jl_remark);
        panLab.add(jTA_remark);

        panLab.add(JR_findByName);
        panLab.add(JR_findByCategory);
        panLab.add(JR_findByEmployer);
        panLab.add(jT_find);
        panLab.add(btn_find);

        this.add(jsp, BorderLayout.NORTH);
        this.add(panLab, BorderLayout.CENTER);
        this.add(panBtn, BorderLayout.SOUTH);

        // 获取表里的值
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String id, job_name, categoryname, employername, demand, hired, remark;
                int selRow = table.getSelectedRow();
                id = table.getValueAt(selRow, 0).toString().trim();
                job_name = table.getValueAt(selRow, 1).toString().trim();
                categoryname = table.getValueAt(selRow, 2).toString().trim();
                employername = table.getValueAt(selRow, 3).toString().trim();
                demand = table.getValueAt(selRow, 4).toString().trim();
                hired = table.getValueAt(selRow, 5).toString().trim();
                remark = table.getValueAt(selRow, 6).toString().trim();
                jT_jobId.setText(id);
                jT_jobName.setText(job_name);
                JC_Category.setSelectedItem(categoryname);
                JC_employer.setSelectedItem(employername);
                jT_demandNum.setText(demand);
                jT_hiredNum.setText(hired);
                jTA_remark.setText(remark);
            }
        });

        btn_find.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (JR_findByName.isSelected()) {
                    String s = jT_find.getText().trim();
                    @Language("MySQL")
                    String sql = "select job_id, job_name, category_name, employer_name, demand_num, hired_num, remark from job_info "
                            + "LEFT JOIN job_category jc ON job_info.category_id = jc.category_id  "
                            + "LEFT JOIN employer e on e.employer_id = job_info.employer_id"
                            + " where job_name like '%"
                            + s
                            + "%'";
                    model = new MyModel(sql);
                    table.setModel(model);
                    for (int i = 0; i < table_title.length; i++) {
                        table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
                    }
                    DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                    r.setHorizontalAlignment(JLabel.CENTER);
                    table.setDefaultRenderer(Object.class, r);
                } else if (JR_findByEmployer.isSelected()) {
                    String s = jT_find.getText().trim();
                    @Language("MySQL")
                    String sql = "select job_id,job_name, category_name, employer_name, demand_num, hired_num, remark from job_info "
                            + "LEFT JOIN job_category jc ON job_info.category_id = jc.category_id  "
                            + "LEFT JOIN employer e on e.employer_id = job_info.employer_id"
                            + " where e.employer_name like '%"
                            + s
                            + "%'";
                    model = new MyModel(sql);
                    table.setModel(model);
                    for (int i = 0; i < table_title.length; i++) {
                        table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
                    }
                    DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                    r.setHorizontalAlignment(JLabel.CENTER);
                    table.setDefaultRenderer(Object.class, r);
                } else {
                    String s = jT_find.getText().trim();
                    @Language("MySQL")
                    String sql = "select job_id,job_name, category_name, employer_name, demand_num, hired_num, remark from job_info "
                            + "LEFT JOIN job_category jc ON job_info.category_id = jc.category_id  "
                            + "LEFT JOIN employer e on e.employer_id = job_info.employer_id"
                            + " where category_name like '%"
                            + s
                            + "%'";
                    model = new MyModel(sql);
                    table.setModel(model);
                    for (int i = 0; i < table_title.length; i++) {
                        table.getColumnModel().getColumn(i).setHeaderValue(table_title[i]);
                    }
                    DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                    r.setHorizontalAlignment(JLabel.CENTER);
                    table.setDefaultRenderer(Object.class, r);
                }
            }
        });

        btn_change.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                int job_id = Integer.parseInt(jT_jobId.getText().trim());
                String job_name = jT_jobName.getText().trim();

                String Categoryname = JC_Category.getSelectedItem().toString();
                try {
                    categoryid = seleCategoryid(Categoryname);
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                String employername = JC_employer.getSelectedItem().toString();
                try {
                    employerid = SelectEmlployerId(employername);
                } catch (SQLException e) {
                    e.printStackTrace();
                }


                int demand = Integer.parseInt(jT_demandNum.getText().trim());
                int hired = Integer.parseInt(jT_hiredNum.getText().trim());
                String remark = jTA_remark.getText().trim();

                Statement stmt = DBUtil.getStatement();
                String sql = "update job_info set job_name = '"
                        + job_name
                        + "',category_id="
                        + categoryid
                        + ",employer_id="
                        + employerid
                        + ",demand_num="
                        + demand
                        + ",hired_num="
                        + hired
                        + ",remark='"
                        + remark
                        + "'"
                        + "where job_id="
                        + job_id
                        + ";";
                try {
                    stmt.executeUpdate(sql);
                    JOptionPane.showMessageDialog(null, "修改成功。");

                    jT_jobId.setText("");
                    jT_jobName.setText("");
                    JC_Category.setSelectedIndex(-1);
                    JC_employer.setSelectedIndex(-1);
                    jT_demandNum.setText("");
                    jT_hiredNum.setText("");
                    jTA_remark.setText("");
                    // 实时更新表
                    @Language("MySQL")
                    String updateSQL = "SELECT job_id,job_name,category_name,employer_name,demand_num,hired_num,remark FROM job_info " +
                            "LEFT JOIN job_category jc ON job_info.category_id = jc.category_id " +
                            "left join employer e ON e.employer_id = job_info.employer_id;";
                    model = new MyModel(updateSQL);
                    table.setModel(model);
                    String[] tableTitle = {"职业编号", "职业名", "类别", "企业", "需求", "已招", "备注"};
                    for (int i = 0; i < tableTitle.length; i++) {
                        table.getColumnModel().getColumn(i).setHeaderValue(tableTitle[i]);
                    }
                    DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                    r.setHorizontalAlignment(JLabel.CENTER);
                    table.setDefaultRenderer(Object.class, r);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });

        btn_delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                int jobid = Integer.parseInt(jT_jobId.getText().trim());
                int result = JOptionPane.showConfirmDialog(null, "确定删除吗?", "提示", JOptionPane.YES_NO_OPTION);
                if (result == JOptionPane.YES_OPTION) {
                    Statement stmt = DBUtil.getStatement();
                    String sql = "delete from job_info where job_id = " + jobid + ";";
                    @Language("MySQL")
                    String existSql = "select job_id from job_match where job_id=" + jobid + ";";
                    try {
                        ResultSet rs = stmt.executeQuery(existSql);
                        if (!rs.next()) {
                            stmt.executeUpdate(sql);
                            JOptionPane.showMessageDialog(null, "已删除！");
                            jT_jobId.setText("");
                            jT_jobName.setText("");
                            JC_Category.setSelectedIndex(-1);
                            JC_employer.setSelectedIndex(-1);
                            jT_demandNum.setText("");
                            jT_hiredNum.setText("");
                            jTA_remark.setText("");
                            // 实时更新表格数据
                            @Language("MySQL")
                            String sql2 = "SELECT job_id,job_name,category_name,employer_name,demand_num,hired_num,remark FROM job_info " +
                                    "LEFT JOIN job_category jc ON job_info.category_id = jc.category_id " +
                                    "left join employer e ON e.employer_id = job_info.employer_id";
                            model = new MyModel(sql2);
                            table.setModel(model);
                            String[] tableTitle = {"职业编号", "职业名", "类别", "企业", "需求", "已招", "备注"};
                            for (int i = 0; i < tableTitle.length; i++) {
                                table.getColumnModel().getColumn(i).setHeaderValue(tableTitle[i]);
                            }
                            DefaultTableCellRenderer r = new DefaultTableCellRenderer();
                            r.setHorizontalAlignment(JLabel.CENTER);
                            table.setDefaultRenderer(Object.class, r);
                        } else {
                            ImageIcon errorImg = new ImageIcon("src/images/error.png");
                            errorImg.setImage(errorImg.getImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT));
                            JOptionPane.showMessageDialog(null, "该职业已有员工被招聘，无法删除！", "错误", JOptionPane.ERROR_MESSAGE, errorImg);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } else {
                    dispose();
                }
            }
        });

    }

    class MyModel extends AbstractTableModel {
        private int row;
        private int column;
        private ResultSet rs;
        private Statement stmt;

        public MyModel(@Language("MySQL") String sql) {
            stmt = DBUtil.getStatement();
            try {
                rs = stmt.executeQuery(sql);
                rs.last();// 将光标移到最后一行
                row = rs.getRow();// 获取行号(最大行索引)
                ResultSetMetaData rsmd = rs.getMetaData();// 通过结果集对象来获取
                column = rsmd.getColumnCount();// 获取列数
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getColumnCount() {
            return column;
        }

        @Override
        public int getRowCount() {
            return row;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object value = null;
            try {
                rs.absolute(rowIndex + 1);
                value = rs.getString(columnIndex + 1);// 获取表里的数据
            } catch (Exception e) {
                e.printStackTrace();
            }
            return value;
        }
    }

    public Vector<String> getCategory_name() throws SQLException {
        Vector<String> Category_name = new Vector<String>();
        String sql = "SELECT category_name from job_category ORDER BY category_id";
        Statement stmt = DBUtil.getStatement();
        ResultSet rs1 = stmt.executeQuery(sql);
        while (rs1.next()) {
            Category_name.add(rs1.getString("category_name"));
        }
        DBUtil.closeMySQL();// 关闭连接
        return Category_name;
    }

    public Vector<String> getEmployer_name() throws SQLException {
        Vector<String> Employer_name = new Vector<String>();
        String sql = "SELECT employer_name from employer ORDER BY employer_id";
        Statement stmt = DBUtil.getStatement();
        ResultSet rs1 = stmt.executeQuery(sql);
        while (rs1.next()) {
            Employer_name.add(rs1.getString("employer_name"));
        }
        DBUtil.closeMySQL();// 关闭连接
        return Employer_name;
    }

    /**
     * @return 类别id
     * @throws SQLException
     * @employername 类别名称
     */
    public int seleCategoryid(String name) throws SQLException {
        @Language("MySQL")
        String sql = "SELECT category_id from job_category WHERE category_name='" + name + "';";
        int count = 0;
        Statement pr = DBUtil.getStatement();
        ResultSet rs = pr.executeQuery(sql);
        while (rs.next()) { // 遍历数据库的数据
            count = rs.getInt(1);
        }
        DBUtil.closeMySQL();// 关闭连接
        return count;
    }

    /**
     * @return 企业id
     * @throws SQLException
     * @employername 企业名称
     */
    public int SelectEmlployerId(String employerName) throws SQLException {
        @Language("MySQL")
        String sql = "SELECT employer_id from employer WHERE employer_name='" + employerName + "';";
        int count = 0;
        Statement pr = DBUtil.getStatement();
        ResultSet rs = pr.executeQuery(sql);
        while (rs.next()) { // 遍历数据库的数据
            count = rs.getInt(1);
        }
        DBUtil.closeMySQL();// 关闭连接
        return count;
    }
}
